package com.pig4cloud.pig.common.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数字处理工具类
 */
public class NumberUtil {

	private static final Logger logger = LoggerFactory.getLogger(NumberUtil.class);

	/**
	 * 取精度
	 * @param num
	 * @param scale
	 */
	public static BigDecimal setScale(BigDecimal num, int scale) {
		return setScale(num, scale, BigDecimal.ROUND_HALF_UP);
	}
	public static BigDecimal setScale(BigDecimal num, int scale, int roundingMode) {
		if (num == null) {
			return BigDecimal.ZERO;
		}
		return num.setScale(scale, roundingMode);
	}
	public static Double setScale(Double num, int scale, int roundingMode) {
		if (num == null) {
			return 0D;
		}
		return BigDecimal.valueOf(num).setScale(scale, roundingMode).doubleValue();
	}


	/**
	 * 判断字符串是否为数值
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		// 该正则表达式可以匹配所有的数字 包括负数
		Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
		String bigStr;
		try {
			bigStr = new BigDecimal(str).toString();
		} catch (Exception e) {
			return false;//异常 说明包含非数字。
		}

		Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

}
